const state = {
  connections: [],
  activeConnection: null,
  connectionStatus: '未连接'
}

const mutations = {
  ADD_CONNECTION(state, connection) {
    state.connections.push({
      ...connection,
      id: `conn_${Date.now()}`,
      createdAt: new Date().toISOString()
    })
  },
  
  UPDATE_CONNECTION(state, { id, data }) {
    const index = state.connections.findIndex(c => c.id === id)
    if (index > -1) {
      state.connections[index] = { ...state.connections[index], ...data }
    }
  },
  
  REMOVE_CONNECTION(state, id) {
    state.connections = state.connections.filter(c => c.id !== id)
    if (state.activeConnection?.id === id) {
      state.activeConnection = null
      state.connectionStatus = '未连接'
    }
  },
  
  SET_ACTIVE_CONNECTION(state, connection) {
    state.activeConnection = connection
  },
  
  SET_CONNECTION_STATUS(state, status) {
    state.connectionStatus = status
  }
}

const actions = {
  addConnection({ commit }, connection) {
    commit('ADD_CONNECTION', connection)
  },
  
  updateConnection({ commit }, payload) {
    commit('UPDATE_CONNECTION', payload)
  },
  
  removeConnection({ commit }, id) {
    commit('REMOVE_CONNECTION', id)
  },
  
  setActiveConnection({ commit }, connection) {
    commit('SET_ACTIVE_CONNECTION', connection)
    commit('SET_CONNECTION_STATUS', connection ? '已连接' : '未连接')
  },
  
  updateConnectionStatus({ commit }, status) {
    commit('SET_CONNECTION_STATUS', status)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}